package me.lx

import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.os.SystemClock
import android.util.Log
import android.view.KeyEvent
import android.webkit.JavascriptInterface
import android.webkit.WebSettings
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.Gson
import com.tencent.smtt.export.external.interfaces.WebResourceRequest
import com.tencent.smtt.export.external.interfaces.WebResourceResponse
import com.tencent.smtt.sdk.*
import com.webuy.fast.webview.FastWebView
import com.webuy.fast.webview.FastWebViewPool
import com.webuy.fast.webview.config.CacheConfig
import com.webuy.fast.webview.config.DefaultMimeTypeFilter
import com.webuy.fast.webview.config.FastCacheMode
import timber.log.Timber
import java.io.File

/**
 * Created by Ryan
 * at 2019/11/4
 */
class WebViewActivity : AppCompatActivity() {
    private var fastWebView: FastWebView? = null
    private var initStartTime: Long = 0
    private var startTime: Long = 0
    @SuppressLint("SetJavaScriptEnabled", "AddJavascriptInterface")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        FastWebView.setDebug(true)
        Timber.d("------------- start once load -------------")
        startTime = SystemClock.uptimeMillis()
        initStartTime = SystemClock.uptimeMillis()
        fastWebView = if (sUseWebViewPool) {
            FastWebViewPool.acquire(this)
        } else {
            Timber.d("create new webview instance.")
            FastWebView(this)
        }
        fastWebView!!.webChromeClient = MonitorWebChromeClient()
        fastWebView!!.webViewClient = MonitorWebViewClient()
        setContentView(fastWebView)
        fastWebView!!.isFocusable = true
        fastWebView!!.isFocusableInTouchMode = true
        val webSettings = fastWebView!!.settings
        webSettings.javaScriptEnabled = true
        webSettings.domStorageEnabled = true
        webSettings.allowFileAccess = true
        webSettings.useWideViewPort = true
        webSettings.loadWithOverviewMode = true
        webSettings.setSupportZoom(false)
        webSettings.builtInZoomControls = false
        webSettings.displayZoomControls = false
        webSettings.defaultTextEncodingName = "UTF-8"
        webSettings.blockNetworkImage = true

        // 设置正确的cache mode以支持离线加载
        val cacheMode =
            if (NetworkUtils.isAvailable(this)) com.tencent.smtt.sdk.WebSettings.LOAD_DEFAULT else com.tencent.smtt.sdk.WebSettings.LOAD_CACHE_ELSE_NETWORK
        webSettings.cacheMode = cacheMode
        //  webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        var cache: String? = null
        cache = if (cacheMode == com.tencent.smtt.sdk.WebSettings.LOAD_DEFAULT) {
            "默认"
        } else {
            "缓存存在就加载缓存  或者 网络 "
        }
        Timber.d("当前缓存模式: $cache")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            webSettings.setAllowFileAccessFromFileURLs(true)
            webSettings.setAllowUniversalAccessFromFileURLs(true)
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val cookieManager = CookieManager.getInstance()
            cookieManager.setAcceptThirdPartyCookies(fastWebView, true)
            webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
        }
        val config = CacheConfig.Builder(this)
            .setCacheDir(cacheDir.toString() + File.separator + "custom")
            .setExtensionFilter(CustomMimeTypeFilter())
            .build()
        fastWebView!!.setCacheMode(FastCacheMode.FORCE, config)
        fastWebView!!.addResourceInterceptor { chain -> chain.process(chain.request) }
        fastWebView!!.addJavascriptInterface(this, "android")
        val headers: MutableMap<String, String> = HashMap()
        headers["custom"] = "test"
        var url = "https://github.com/luoxiong94"
        url = "http://api-test.yunx.ruhrtech.com/luoxiong_1360768_1400900.html"
        CookieSyncManager.createInstance(this)
        val cookieManager = CookieManager.getInstance()
        cookieManager.setAcceptCookie(true)
        cookieManager.removeSessionCookie() // 移除旧的[可以省略]
        cookieManager.setCookie(url, "custom=12345678910;")
        CookieSyncManager.getInstance().sync()
        val fastCookieManager = fastWebView!!.fastCookieManager
        fastCookieManager.addRequestCookieInterceptor { url, originCookies ->
            for (cookie in originCookies) {
                Timber.d("request cookies: $cookie")
            }
            originCookies
        }
        fastCookieManager.addResponseCookieInterceptor { url, originCookies ->
            for (cookie in originCookies) {
                Timber.d("response cookies: $cookie")
            }
            originCookies
        }
        fastWebView!!.loadUrl(url, headers)
    }

    @JavascriptInterface
    fun sendResource(timing: String?) {
        val performance = Gson().fromJson(timing, Performance::class.java)
        Timber.d("网络请求花费: " + (performance.responseEnd - performance.requestStart) + "ms")
        Timber.d("dom构建时间: " + (performance.domComplete - performance.domInteractive) + "ms.")
        Timber.d("dom显示时间: " + (performance.domContentLoadedEventEnd - performance.navigationStart) + "ms.")
        Timber.d("加载完成时间: " + (performance.loadEventEnd - performance.navigationStart) + "ms.")
    }

    override fun onDestroy() {
        super.onDestroy()
        if (fastWebView != null) {
            if (sUseWebViewPool) {
                FastWebViewPool.release(fastWebView)
            } else {
                fastWebView!!.destroy()
            }
        }
    }

    inner class MonitorWebViewClient : WebViewClient() {
        private var first = true
        override fun onPageFinished(view: WebView, url: String) {
            super.onPageFinished(view, url)
            view.settings.blockNetworkImage = false
            view.loadUrl("javascript:android.sendResource(JSON.stringify(window.performance.timing))")
        }

        override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse {
            if (first) {
                Timber.d("init cost time: " + (SystemClock.uptimeMillis() - initStartTime))
                first = false
            }
            return super.shouldInterceptRequest(view, request)
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (fastWebView!!.canGoBack()) {
                fastWebView!!.goBack()
                return true
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    inner class MonitorWebChromeClient : WebChromeClient() {
        override fun onReceivedTitle(view: WebView, title: String) {
            super.onReceivedTitle(view, title)
            Log.d(TAG, "white screen time: " + (SystemClock.uptimeMillis() - startTime))
        }
    }

    inner class CustomMimeTypeFilter internal constructor() : DefaultMimeTypeFilter()
    companion object {
        private const val TAG = "FastWebView"
        var sUseWebViewPool = false
    }
}